/** 
 * 队列式状态机
 * Author      : donggang
 * Create Time : 2016.11.20
*/
var STATE_NODE_NAME        = "StateNode";
var STATE_EVALUATE_INITIAL = "evaluate_initial";
var STATE_EVALUATE_FINAL   = "evaluate_final";

var state = require("state");

// state.console = console;

module.exports = cc.Class({
    ctor : function(){
        this._states  = [];
        this._root    = new state.StateMachine("root");                                                         // 状态机对象
        this._initial = new state.PseudoState("initial", this._root, state.PseudoStateKind.Initial);            // 最初状态
        this._final   = new state.FinalState("final", this._root);                                              // 最终状态
        this._ready   = new state.State("ready", this._root);                                                   // 预备状态
    },

    /**
     * 创建状态节点
     * @param name(string)      节点名（唯一标识）
     * @param entry(function)   实体处理回调
     */
    push : function(entry){
        var self = this;
        var name = STATE_NODE_NAME + this._states.length;
        var node = new state.State(name, this._root);
        node.entry(entry);
        this._states.push(node);
    },

    /** 初始划队列状态机 */
    init : function(){
        if (this._states.length == 0) return;

        this._index = 0;        // 状态进度

        this._initial.to(this._ready);

        // 准备状态条状到逻辑状态
        this._ready.to(this._states[0]).when(function(message){              
            return message == STATE_EVALUATE_INITIAL;
        });

        for (var i = 1; i < this._states.length; i++){
            var node1  = this._states[i - 1];
            var node2  = this._states[i];
            var transition = node1.to(node2);
            transition.when(function(message){              // 状态转换条件
                return message == true;
            }.bind(this));
        }

        // 最后跳转到终状态
        var endIndex = this._states.length - 1
        var node     = this._states[endIndex];
        node.to(this._ready).when(function(message){
            return message != STATE_EVALUATE_FINAL;
        });
        node.to(this._final).else();

        this._instance = new state.StateMachineInstance("instance");
        state.validate(this._root);
        state.initialise(this._root, this._instance);
    },

    /** 开始状态流程 */
    start : function(){
        state.evaluate(this._root, this._instance, STATE_EVALUATE_INITIAL);
    },

    /** 跳转到下一个状态 */
    next : function(){
        var id = setTimeout(function(){
            state.evaluate(this._root, this._instance, true);
            clearTimeout(id);
        }.bind(this), 0);
    },

    /** 终止状态 */
    end : function(){
        var id = setTimeout(function(){
            state.evaluate(this._root, this._instance, STATE_EVALUATE_FINAL);
            clearTimeout(id);
        }.bind(this), 0);
    }
});
